﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EventBusHelper
{
    public static class ImageHelper
    {

        public static void CreateImage(string cardNumber)
        {
            // 定义目标尺寸
            int targetWidth = 240;
            int targetHeight = 295;

            using (Bitmap temp = new Bitmap(targetWidth, targetHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
            {
                Graphics g = Graphics.FromImage(temp);
                g.Clear(Color.White);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                Bitmap imageForBmp = null;

                try
                {
                    imageForBmp = new Bitmap(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + cardNumber + ".jpg");

                    // 计算放大或缩小所需的尺寸
                    float scale = Math.Max((float)targetWidth / imageForBmp.Width, (float)targetHeight / imageForBmp.Height);
                    int newWidth = (int)(imageForBmp.Width * scale);
                    int newHeight = (int)(imageForBmp.Height * scale);

                    // 计算绘制位置，使图像填充整个目标位图
                    int x = (targetWidth - newWidth) / 2;
                    int y = (targetHeight - newHeight) / 2;

                    // 使用填充方式绘制图像
                    g.DrawImage(imageForBmp, x, y, newWidth, newHeight);
                }
                catch (Exception ex)
                {
                   
                    return; // 结束方法
                }
                finally
                {
                    imageForBmp?.Dispose(); // 确保释放原始图像资源
                }

                try
                {
                    // 保存生成的图像
                    temp.Save(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "stamp2.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                }
                catch (Exception ex)
                {
                   
                }
                finally
                {
                    g.Dispose(); // 确保 Graphics 对象被释放
                }
            }
        }
    }
}
